#include "shareManager.h"


#include <QDebug>
BufferHandle::BufferHandle(QObject *parent) :
    QThread(parent)
{
}

void BufferHandle::run()
{
    while(true)
    {
        serialBufferHandle(sharePointer->rxBuffer);
    }
}

void BufferHandle::startThread()
{
    start();
}


void BufferHandle::serialBufferHandle(QByteArray &buf)
{
    int nFramePos = 0;
    //没找到帧结束符
    if(!buf.contains('\n'))
    {return;}

    //讲一帧数据取出并从缓冲区移除
    nFramePos = buf.indexOf('\n');
    QByteArray tmpBuf = buf.mid(0, nFramePos + 1);// +1 -> \n
    buf.remove(0, nFramePos + 1);

    //1.判断帧头
    if(tmpBuf[0] != (char)0x55 || tmpBuf[1] != (char)0x55)
    {return;}//错误帧

    //2.校验长度
    if((quint8)tmpBuf[3] != (tmpBuf.size()-5))
    {return;}//实际长度 != 接收长度

    //3.提取功能字
    char funcWord = tmpBuf[2];

    //4.根据功能字解码
    switch(funcWord)
    {
    case (char)0xA2 :
        AHRSHandle(tmpBuf);
        break;

    case (char)0xA3 :
        RCHandle(tmpBuf);
        break;

    case (char)0xA4 :
        GPSHandle(tmpBuf);
        break;

    default : break;
    }

    //防止buffer爆炸
    if(buf.size() > 128)//每次都是从0mid然后remove，这个仅是为没有'\n'的情况判断
    {buf.clear();}
}

void BufferHandle::RCHandle(const QByteArray &buf)
{
    if((quint8)buf[3] != (buf.size()-5))
    {return;}//实际长度 != 接收到的数据长度

    char *p = (char*)(&(sharePointer->RC_Values.CH1));
    for(int i = 4; i < buf.size()-1; i++)
    {
      *p++ = (char)buf[i];
    }
}

void BufferHandle::AHRSHandle(const QByteArray &buf)
{
    if((quint8)buf[3] != (buf.size()-5))
    {return;}

    char *p = (char *)&sharePointer->AHRS_values.YAW;
    for(int i = 4; i < buf.size()-1; i++)
    {
      *p++ = (char)buf[i];
    }
}

void BufferHandle::GPSHandle(const QByteArray &buf)
{
    if((quint8)buf[3] != (buf.size()-5))
    {return;}

    char *p = (char *)&sharePointer->GPS_values.longtitude;
    for(int i = 4; i < buf.size()-1; i++)
    {
      *p++ = (char)buf[i];
    }
}

